<?php
namespace app\index\controller;

use think\Controller;
use think\Db;
use think\Request;
use think\Session;
use app\index\model\Nav;
use app\index\model\User;
use app\index\model\Code;

class Login extends Controller
{
	public function login()
	{
		$user = new User();
		$mobile = input('post.mobile');
		$password = MD5(input('post.password'));
		if ($mobile == false || $password == false) {
			$data = [
				'msg' => '账号密码有误！',
				'result' => 400, 
			];
			return json($data);
		}
        $where = array('mobile'=>$mobile,'password'=>$password);
        $member = $user->get_MemberOne($where);
        if (empty($member)) {
            $data = [
                'msg' => '账号密码不正确！',
                'result' => 400,
            ];
            return json($data);
        }
        $token = $user->getToken($member['user_id']);
        $member['token'] = $token;
        if ($member == false) {
            $data = [
                'msg' => '账号不存在！',
                'result' => 400,
            ];
            return json($data);
        }else{
            Session::set('userId',$member['user_id']);
            Session::set('token',$member['token']);
            $data = [
                'msg' => '登陆成功！',
                'result' => 200,
                'data' => $member
            ];
            return json($data);
        }
	}

	/**
	 * 注册接口
	 * @access public
	 * @param mobile 手机号码
	 * @param password 密码
	 * @return json
	 */
	public function register()
	{
		$user = new User();
		$member = array();
		$member['mobile'] = input('post.mobile');
		$member['password'] = MD5(input('put.password'));
		$member['reg_time'] = time();
		$mobile = input('put.mobile');
		$mobilecode = input('post.code');
        $type = input('put.type');
        $is_code = $this->smsRegister($mobilecode,$mobile,$type);
        if (!$is_code['stats']) {
            $data = [
                'msg'   =>  $is_code['msg'],
                'stats' =>  false
            ];
            return json($data);
        }
		//查询手机号码是否注册过了
        $presence = $user->get_MemberOne(array('mobile'=>$mobile));
        if(!empty($presence)){
            $data = [
                'msg'   =>  '手机号码已注册！',
                'stats' =>  false
            ];
            return json($data);
        }
		$insert_id = $this->register_Add($member);
        if ($insert_id) {
        	//添加关系表
        	$userId = Db::name('users')->getLastInsID();
        	$is_gather = $user->getMemberGatherAdd($userId);
        	$member_info = $user->get_MemberOne(array('user_id'=>$userId));
            Session::set('member_id',$userId);
            $data = [
                'msg'   =>  '注册成功',
                'stats' =>  true,
                'data'	=>	$member_info
            ];
            return json($data);
        }else{
            $data = [
                'msg'   =>  '注册失败',
                'stats' =>  false
            ];
            return json($data);
        }
	}

	private function smsRegister($mobilecode,$mobile,$type)
	{
		$m_code = new Code();
		$condition = array();
        $condition['code']     = $mobilecode;
        $condition['mobile']   = $mobile;
        $condition['scene']    = $type;
        $sms_log = $m_code->getSmsInfo($condition);
        if (!empty($sms_log) && $sms_log['addtime']+60 < time()) {
            $data = [
                'msg'   =>  '验证码已过期！',
                'stats' =>  false
            ];
            return $data;
        }elseif ($sms_log['code'] == $mobilecode) {
            $data = [
                'msg'   =>  '验证码正确！',
                'stats' =>  true
            ];
            return $data;
        }else{
            $data = [
                'msg'   =>  '验证码错误！',
                'stats' =>  false
            ];
            return $data;
        }
	}

	/**
     * 添加会员
     * @param array $member_info
     */
    private function register_Add($member_info)
    {
        $member_list = array();
        $member_list['Email'] = '';
        $member_list['password'] = $member_info['password'];
        $member_list['reg_time'] = $member_info['reg_time'];
        $member_list['last_ip']  = Request::instance()->ip();
        $member_list['mobile']   = $member_info['mobile'];
        $member_list['level']   = 0;
        $member_list['rank_id']   = 0;
        $member_list['is_author']   = 0;
        if ($member_info['mobile']) {
            $member_list['mobile_validated'] = 1;
        }
        $user = new User();
        $result = $user->getMemberInsert($member_list);
        return $result;
    }

	/**
     * 短信接口
     * @access public
     * @param mobile 手机号码
     */
	public function sendCaptcha()
	{
		$m_code = new Code();
        $code = rand(100000, 999999);
        $mobile = input('post.mobile');
        $type = input('post.type');
        $apikey = '471626d9fb37f47ce319f8ab6fea189c';
        $text = '【盈链科技】 您的验证码是 '.$code;
        $res = $this->SendSms($text,$mobile,$apikey);
        if ($res[0]['code'] != false) {
            $data = [
                'msg'   =>  $res[0]['msg'],
                'stats' =>  $res[0]['code']
            ];
            return json($data);
        }
        
		//判断一分钟请求的次数
		$sms_log = $this->ipCaptcha($type);
        if (!empty($sms_log) && $sms_log['addtime']+60 > time()) {
            $data = [
                'msg'   =>  '一分钟之内请求时间过快！',
                'stats' =>  false
            ];
            return json($data);
        }
		//使用接口
		
		//接口返回成功
		if ($code) {
			//将code存入数据库中sms_log
			$code_log['mobile'] = $mobile;
			$code_log['code'] = $code;
			$code_log['addtime'] = time();
			$code_log['log_ip'] = Request::instance()->ip();
			if ($type == 1) {
				$code_log['scene'] = 1;//1为注册账号，2为找回密码
				$code_log['msg'] = '注册账号';
			}else{
				$code_log['scene'] = 2;//1为注册账号，2为找回密码
				$code_log['msg'] = '找回密码';
			}
			$is_code = $m_code->get_SmsCode($code_log);
			//存储是否正确
			if ($is_code) {
				$data = [
					'msg'	=>	'验证码发送成功',
					'result'	=>	200
				];
				return json($data);
			}else{
				$data = [
					'msg'	=>	'系统堵塞501',
					'result'	=>	400
				];
				return json($data);
			}
		}else{
			$data = [
				'msg'	=>	'验证码发送失败',
				'result'	=>	400
			];
			return json($data);
		}

	}

	/**
     * 按IP查询手机验证码
     * @param string $log_type
     * @return array
     */
    private function ipCaptcha($type = 1)
    {
        $condition = array();
        $condition['log_ip'] = Request::instance()->ip();
        $scene = $type;
        if ($scene > 0) {
            $condition['scene'] = $scene;//短信类型:1为注册,2为登录,3为找回密码
        }
        $model_sms_log = new Code();
        $sms_log = $model_sms_log->getSmsInfo($condition);
        return $sms_log;
    }

	/**
     * 生成随机字符串
     * @access public
     * @param length 字符串长度
     */
	public function str_rand($length = 6, $char = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
		if(!is_int($length) || $length < 0) {
			return false;
		}
		$string = '';
		for($i = $length; $i > 0; $i--) {
			$string .= $char[mt_rand(0, strlen($char) - 1)];
		}
		return $string;
	}

    /**
     * 云片网短信接口
     * @access public
     * @param tpl_content 内容
     * @param send_mobile 手机号
     * @param apikey api密钥
     */
    public function SendSms($tpl_content,$send_mobile,$apikey)
    {

        $this->yunpian_appkey = $apikey;//云片账户appkey

        // $this->yunpian_secret = env('yunpianSecretXYZ');//云片账户secret

        //初始化
        header("Content-type:text/html;charset=utf-8");
        $ch    = curl_init();

        $data=array('text'=>$tpl_content,'apikey'=>$this->yunpian_appkey,'mobile'=>$send_mobile);

        curl_setopt ($ch, CURLOPT_URL, 'https://sms.yunpian.com/v2/sms/single_send.json');

        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));

        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept:text/plain;charset=utf-8', 'Content-Type:application/x-www-form-urlencoded', 'charset=utf-8'));

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($ch, CURLOPT_TIMEOUT, 10);

        curl_setopt($ch, CURLOPT_POST, 1);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);



        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));

        $send_data = curl_exec($ch);

        curl_close($ch);

        //解析返回结果（json格式字符串）

        $backmassage = json_decode($send_data,true);

        //这里是写在了job里面所以记了个日志可忽略！

        // Log::info('smsmessagelog: '.$send_data);

        return [$backmassage,$send_data];

    }
}